<!-- C:\Users\王硕\Desktop\毕设\housing-rental-system-frontend\新建文件夹\vue-demo\src\views\UpdataPwd.vue -->
<template>
  <div class="page-container">
    <el-card class="form-container">
      <h2 class="title">修改密码</h2>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="form.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="8-20位，需包含字母和数字"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading">
            {{ loading ? "提交中..." : "立即修改" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import api from "@/api";
import { useRouter } from "vue-router"; // 新增路由引入
import { useUserStore } from "@/stores/user"; // 引入用户存储

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const form = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 验证规则
const validatePassword = (rule, value, callback) => {
  const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/;
  if (!regex.test(value)) {
    callback(new Error("需包含字母和数字，8-20位"));
  } else {
    callback();
  }
};

const validateConfirm = (rule, value, callback) => {
  if (value !== form.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const rules = reactive({
  oldPassword: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { validator: validateConfirm, trigger: "blur" },
  ],
});

// 提交处理
const formRef = ref(null);
const loading = ref(false);

const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    loading.value = true;

    // 调用接口
    const response = await api.auth.changePassword({
      oldPassword: form.oldPassword,
      newPassword: form.newPassword,
    });

    // 明确检查返回状态码
    if (response.code == 200) {
      ElMessage.success("密码修改成功！");
      // 跳转登录页// 清除用户信息（关键新增代码）
      userStore.clearUserInfo();
      localStorage.removeItem("token");

      // 跳转到登录页（带提示参数）
      router.push({
        path: "/login",
        query: {
          message: "密码已更新，请使用新密码登录",
          type: "success",
        },
      });
    } else {
      ElMessage.error(response.message || "密码修改失败");
    }
  } catch (error) {
    // 处理 HTTP 状态码错误
    console.error("密码修改失败：", error);
    if (error.response && error.response.status == 401) {
      ElMessage.error("旧密码错误");
    } else {
      ElMessage.error("修改失败：" + error.message);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.page-container {
  max-width: 600px;
  margin: 40px auto;
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

.form-container {
  padding: 30px 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-button {
  width: 100%;
  margin-top: 20px;
}
</style>
